from flask import Flask, render_template, Response, request, jsonify, stream_with_context
import RPi.GPIO as GPIO
import cv2
from components.drv8833 import Motor
from components.servo_dual_axis import Dual_Axis

# opencv
from components.cv_camera import CameraStream
from components.cv_image import add_servo_angle_to_image

# add dual axis laser
from components.laser_shot import Laser
from components.dual_axis_laser import Dual_Axis_Laser


GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

motor = Motor(5,6,27,17)
# horizontal_Pin,horizontal_init_angle,vertical_Pin,vertical_init_angle
dual_axis=Dual_Axis(18,90,19,80)
camera_cap = CameraStream().start()

# laser
laser = Laser(26)  # singal
laser_vertical_servo_Pin=13
laser_vertical_servo_init_angle=90
# stepper_in1,stepper_in2,stepper_in3, stepper_in4,
dual_axis_laser = Dual_Axis_Laser(21, 20, 7, 8, laser_vertical_servo_Pin, laser_vertical_servo_init_angle)

def gen_frame():
    """Video streaming generator function"""
    while camera_cap:
        frame = camera_cap.read()
         # modified the frame
        frame=add_servo_angle_to_image(frame,dual_axis)
        convert = cv2.imencode('.jpg', frame)[1].tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + convert + b'\r\n')  # concate frame one by one and show result

app = Flask(__name__)


@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen_frame(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/', methods=['GET', 'POST'])
def main():
    return render_template("index.html")

@app.route('/car_action', methods=['GET'])
def car_action():
    m_action = int(request.args.get('action'))
    motor.action(m_action)
    return jsonify({'motor status':m_action})

@app.route('/dual_axis_action', methods=['GET'])
def dual_axis_action():
    dual_axis_action = int(request.args.get('action'))
    dual_axis.action(dual_axis_action)
    return jsonify({'dual_axis servo status':dual_axis_action})

@app.route('/laser_action', methods=['GET'])
def laser_action():
    laser_action = int(request.args.get('action'))
    laser.action(laser_action)
    return jsonify({'laser status': laser_action})

@app.route('/dual_axis_laser_action', methods=['GET'])
def dual_axis_laser_action():
    dual_axis_laser_action = int(request.args.get('action'))
    dual_axis_laser.action(dual_axis_laser_action)
    return jsonify({'dual axis laser status': dual_axis_laser_action})

@app.route('/opencv_action', methods=['GET'])
def opencv_action():
    opencv_action = int(request.args.get('action'))
    camera_cap.cur_opencv_action=opencv_action
    return jsonify({'opencv status':opencv_action})

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=False)
    cv2.destroyAllWindows()
    GPIO.cleanup()

